package com.regvision.contacts.ui.adapter;

import java.util.List;
import com.regvision.contacts.R;
import com.regvision.contacts.domain.ContactModel;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

@SuppressLint("DefaultLocale") public class ContactAdapter extends BaseAdapter {

	private Context mContext;
	private int resource;
	private List<ContactModel> list;

	public ContactAdapter(Context context, int resource, List<ContactModel> list) {
		// TODO Auto-generated constructor stub]
		this.mContext = context;
		this.resource = resource;
		this.list = list;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		Holder holder;
		
		ContactModel info = (ContactModel)getItem(position);
		
		if (convertView == null) {
			convertView = ((LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(resource, null);
			
			holder = new Holder();
			holder.tvName = (TextView) convertView.findViewById(R.id.tv_item_sort);
			holder.tvLetter = (TextView) convertView.findViewById(R.id.tv_char_item_sort);
			
			convertView.setTag(holder);
		} else {
			holder = (Holder)convertView.getTag();
		}

		int section = getSectionForPosition(position);
		//如果当前位置等于该分类首字母的char位置，则认为是第一次出现
		if(position == getPositionForSection(section)) {
			holder.tvLetter.setVisibility(View.VISIBLE);
			holder.tvLetter.setText(info.sortLetters.substring(0, 1));
		} else {
			holder.tvLetter.setVisibility(View.GONE);
		}
		holder.tvName.setText(info.name);
		
		return convertView;
	}
	
	public void updateView(List<ContactModel> list) {
		this.list = list;
		this.notifyDataSetChanged();
	}
	
	class Holder {
		public TextView tvName;
		public TextView tvLetter;
	}
	
	

	/**
	 * 根据ListView的当前位置获取分类的首字母的Char ascii值
	 */
	public int getSectionForPosition(int position) {
		return list.get(position).sortLetters.charAt(0);
	}

	/**
	 * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
	 */
	public int getPositionForSection(int section) {
		for (int i = 0; i < getCount(); i++) {
			String sortStr = list.get(i).sortLetters;
			char firstChar = sortStr.toUpperCase().charAt(0);
			if (firstChar == section) {
				return i;
			}
		}

		return -1;
	}

}
